package com.cskaoyan.controller;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.InfoData;
import com.cskaoyan.bean.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;

/**
 * Authenticate
 */
@RestController
@RequestMapping("admin/auth")
public class AuthController {

    //@RequestMapping("admin/auth/login")
    @PostMapping("/login")
    public BaseRespVo login(@RequestBody LoginUser user) {
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());

        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        Session session = subject.getSession();
        System.out.println("login的sessionId：" + session.getId());
        return BaseRespVo.ok(session.getId());
    }

    @GetMapping("/info")//Get请求请求参数不可能是Json
    public BaseRespVo info(String token) {
        Subject subject = SecurityUtils.getSubject();
        Object primaryPrincipal = subject.getPrincipals().getPrimaryPrincipal();
        Session session = subject.getSession();
        System.out.println("info的sessionId：" + session.getId());
        //查询用户信息的业务，大家自己来写 👉 需要自己来做
        InfoData infoData = new InfoData();
        infoData.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        infoData.setName("admin123");
        ArrayList<String> perms = new ArrayList<>();
        perms.add("*");
        infoData.setPerms(perms);
        ArrayList<String> roles = new ArrayList<>();
        roles.add("超级管理员");
        infoData.setRoles(roles);

        return BaseRespVo.ok(infoData);
    }

}
